home *** CD-ROM | disk | FTP | other *** search
/ The Fatted Calf / The Fatted Calf.iso / Applications / Graphics / Gnuplot / Source / contour.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-03-02  |  41.5 KB  |  1,274 lines

  1. #ifndef lint
  2. static char *RCSid = "$Id: contour.c%v 3.38.2.74 1993/02/19 00:05:24 woo Exp woo $";
  3. #endif
  4.  
  5.  
  6. /* GNUPLOT - contour.c */
  7. /*
  8.  * Copyright (C) 1986 - 1993   Thomas Williams, Colin Kelley
  9.  *
  10.  * Permission to use, copy, and distribute this software and its
  11.  * documentation for any purpose with or without fee is hereby granted, 
  12.  * provided that the above copyright notice appear in all copies and 
  13.  * that both that copyright notice and this permission notice appear 
  14.  * in supporting documentation.
  15.  *
  16.  * Permission to modify the software is granted, but not the right to
  17.  * distribute the modified code.  Modifications are to be distributed 
  18.  * as patches to released version.
  19.  *  
  20.  * This software is provided "as is" without express or implied warranty.
  21.  * 
  22.  *
  23.  * AUTHORS
  24.  * 
  25.  *   Original Software:
  26.  *       Gershon Elber
  27.  * 
  28.  * Send your comments or suggestions to 
  29.  *  info-gnuplot@dartmouth.edu.
  30.  * This is a mailing list; to join it send a note to 
  31.  *  info-gnuplot-request@dartmouth.edu.  
  32.  * Send bug reports to
  33.  *  bug-gnuplot@dartmouth.edu.
  34.  */
  35.  
  36. #include <stdio.h>
  37. #include "plot.h"
  38.  
  39. #define DEFAULT_NUM_OF_ZLEVELS  10  /* Some dflt values (setable via flags). */
  40. #define DEFAULT_NUM_APPROX_PTS  5
  41. #define DEFAULT_BSPLINE_ORDER  3
  42. #define MAX_NUM_OF_ZLEVELS      100 /* Some max. values (setable via flags). */
  43. #define MAX_NUM_APPROX_PTS      100
  44. #define MAX_BSPLINE_ORDER      10
  45.  
  46. #define INTERP_NOTHING   0            /* Kind of interpolations on contours. */
  47. #define INTERP_CUBIC     1                           /* Cubic spline interp. */
  48. #define APPROX_BSPLINE   2                         /* Bspline interpolation. */
  49.  
  50. #define LEVELS_AUTO            0        /* How contour levels are set */
  51. #define LEVELS_INCREMENTAL    1        /* user specified start & incremnet */
  52. #define LEVELS_DISCRETE        2        /* user specified discrete levels */
  53. #define ACTIVE   1                    /* Status of edges at certain Z level. */
  54. #define INACTIVE 2
  55.  
  56. #define OPEN_CONTOUR     1                                 /* Contour kinds. */
  57. #define CLOSED_CONTOUR   2
  58.  
  59. #define EPSILON  1e-5              /* Used to decide if two float are equal. */
  60. #define INFINITY 1e10
  61.  
  62. #ifndef TRUE
  63. #define TRUE     -1
  64. #define FALSE    0
  65. #endif
  66.  
  67. #define DEFAULT_NUM_CONTOURS    10
  68. #define MAX_POINTS_PER_CNTR     100
  69. #define SHIFT_Z_EPSILON        0.000301060 /* Dec. change of poly bndry hit.*/
  70.  
  71. #define abs(x)  ((x) > 0 ? (x) : (-(x)))
  72. #define sqr(x)  ((x) * (x))
  73.  
  74. #ifndef AMIGA_AC_5
  75. extern double sqrt();
  76. #endif /* not AMIGA_AC_5 */
  77. typedef double tri_diag[3];         /* Used to allocate the tri-diag matrix. */
  78. typedef double table_entry[4];           /* Cubic spline interpolation 4 coef. */
  79.  
  80. struct vrtx_struct {
  81.     double X, Y, Z;                       /* The coordinates of this vertex. */
  82.     struct vrtx_struct *next;                             /* To chain lists. */
  83. };
  84.  
  85. struct edge_struct {
  86.     struct poly_struct *poly[2];   /* Each edge belongs to up to 2 polygons. */
  87.     struct vrtx_struct *vertex[2]; /* The two extreme points of this vertex. */
  88.     struct edge_struct *next;                             /* To chain lists. */
  89.     int status, /* Status flag to mark edges in scanning at certain Z level. */
  90.     boundary;                   /* True if this edge is on the boundary. */
  91. };
  92.  
  93. struct poly_struct {
  94.     struct edge_struct *edge[3];           /* As we do triangolation here... */
  95.     struct poly_struct *next;                             /* To chain lists. */
  96. };
  97.  
  98. struct cntr_struct {           /* Contours are saved using this struct list. */
  99.     double X, Y;                          /* The coordinates of this vertex. */
  100.     struct cntr_struct *next;                             /* To chain lists. */
  101. };
  102.  
  103. static int test_boundary;    /* If TRUE look for contours on boundary first. */
  104. static struct gnuplot_contours *contour_list = NULL;
  105. static double crnt_cntr[MAX_POINTS_PER_CNTR * 2];
  106. static int crnt_cntr_pt_index = 0;
  107. static double contour_level = 0.0;
  108. static table_entry *hermit_table = NULL;    /* Hold hermite table constants. */
  109. static int num_of_z_levels = DEFAULT_NUM_OF_ZLEVELS;  /* # Z contour levels. */
  110. static int num_approx_pts = DEFAULT_NUM_APPROX_PTS;/* # pts per approx/inter.*/
  111. static int bspline_order = DEFAULT_BSPLINE_ORDER;   /* Bspline order to use. */
  112. static int interp_kind = INTERP_NOTHING;  /* Linear, Cubic interp., Bspline. */
  113. static int levels_kind = LEVELS_AUTO;  /* auto, incremental, discrete */
  114.  
  115.  
  116. static void gen_contours();
  117. static int update_all_edges();
  118. static struct cntr_struct *gen_one_contour();
  119. static struct cntr_struct *trace_contour();
  120. static struct cntr_struct *update_cntr_pt();
  121. static int fuzzy_equal();
  122. static void gen_triangle();
  123. static struct vrtx_struct *gen_vertices();
  124. static struct edge_struct *gen_edges_middle();
  125. static struct edge_struct *gen_edges();
  126. static struct poly_struct *gen_polys();
  127. static void free_contour();
  128. static void put_contour();
  129. static put_contour_nothing();
  130. static put_contour_cubic();
  131. static put_contour_bspline();
  132. static calc_tangent();
  133. static int count_contour();
  134. static complete_spline_interp();
  135. static calc_hermit_table();
  136. static hermit_interp();
  137. static prepare_spline_interp();
  138. static int solve_tri_diag();
  139. static gen_bspline_approx();
  140. static double fetch_knot();
  141. static eval_bspline();
  142.  
  143. /*
  144.  * Entry routine to this whole set of contouring module.
  145.  */
  146. struct gnuplot_contours *contour(num_isolines, iso_lines,
  147.                  ZLevels, approx_pts, int_kind, order1,
  148.                  levels_kind, levels_list)
  149. int num_isolines;
  150. struct iso_curve *iso_lines;
  151. int ZLevels, approx_pts, int_kind, order1;
  152. int levels_kind;
  153. double *levels_list;
  154. {
  155.     int i;
  156.     struct poly_struct *p_polys, *p_poly;
  157.     struct edge_struct *p_edges, *p_edge;
  158.     struct vrtx_struct *p_vrts, *p_vrtx;
  159.     double x_min, y_min, z_min, x_max, y_max, z_max, z, dz, z_scale = 1.0;
  160.      struct gnuplot_contours *save_contour_list;
  161.  
  162.     num_of_z_levels = ZLevels;
  163.     num_approx_pts = approx_pts;
  164.     bspline_order = order1 - 1;
  165.     interp_kind = int_kind;
  166.  
  167.     contour_list = NULL;
  168.  
  169.     if (interp_kind == INTERP_CUBIC) calc_hermit_table();
  170.  
  171.     gen_triangle(num_isolines, iso_lines, &p_polys, &p_edges, &p_vrts,
  172.         &x_min, &y_min, &z_min, &x_max, &y_max, &z_max);
  173.     crnt_cntr_pt_index = 0;
  174.  
  175.     dz = (z_max - z_min) / (num_of_z_levels + 1);
  176.     z = z_min;
  177.     for (i = 0; i < num_of_z_levels; i++) {
  178.         switch(levels_kind) {
  179.             case LEVELS_AUTO:
  180.                 /* Step from z_min+dz upto z_max-dz in num_of_z_levels times. */
  181.                 z += dz;
  182.                 break;
  183.             case LEVELS_INCREMENTAL:
  184.                 z = levels_list[0] + i * levels_list[1];
  185.                 break;
  186.             case LEVELS_DISCRETE:
  187.                 z = levels_list[i];
  188.                 break;
  189.         }
  190.         contour_level = z;
  191.          save_contour_list = contour_list;
  192.         gen_contours(p_edges, z + dz * SHIFT_Z_EPSILON, x_min, x_max,
  193.                                 y_min, y_max);
  194.          if(contour_list != save_contour_list) {
  195.              contour_list->isNewLevel = 1;
  196.              sprintf(contour_list->label, "%8.3g", z);
  197.          }
  198.     }
  199.  
  200.     /* Free all contouring related temporary data. */
  201.     while (p_polys) {
  202.     p_poly = p_polys -> next;
  203.     free (p_polys);
  204.     p_polys = p_poly;
  205.     }
  206.     while (p_edges) {
  207.     p_edge = p_edges -> next;
  208.     free (p_edges);
  209.     p_edges = p_edge;
  210.     }
  211.     while (p_vrts) {
  212.     p_vrtx = p_vrts -> next;
  213.     free (p_vrts);
  214.     p_vrts = p_vrtx;
  215.     }
  216.  
  217.     if (interp_kind == INTERP_CUBIC) free(hermit_table);
  218.  
  219.     return contour_list;
  220. }
  221.  
  222. /*
  223.  * Adds another point to the currently build contour.
  224.  */
  225. add_cntr_point(x, y)
  226. double x, y;
  227. {
  228.     int index;
  229.  
  230.     if (crnt_cntr_pt_index >= MAX_POINTS_PER_CNTR-1) {
  231.     index = crnt_cntr_pt_index - 1;
  232.     end_crnt_cntr();
  233.     crnt_cntr[0] = crnt_cntr[index * 2];
  234.     crnt_cntr[1] = crnt_cntr[index * 2 + 1];
  235.     crnt_cntr_pt_index = 1; /* Keep the last point as first of this one. */
  236.     }
  237.     crnt_cntr[crnt_cntr_pt_index * 2] = x;
  238.     crnt_cntr[crnt_cntr_pt_index * 2 + 1] = y;
  239.     crnt_cntr_pt_index++;
  240. }
  241.  
  242. /*
  243.  * Done with current contour - create gnuplot data structure for it.
  244.  */
  245. end_crnt_cntr()
  246. {
  247.     int i;
  248.     struct gnuplot_contours *cntr = (struct gnuplot_contours *)
  249.                     alloc((unsigned long)sizeof(struct gnuplot_contours),
  250.                           "gnuplot_contour");
  251.  
  252.     cntr->coords = (struct coordinate GPHUGE *) alloc((unsigned long)sizeof(struct coordinate) *
  253.                               ( unsigned long)crnt_cntr_pt_index,
  254.                            "contour coords");
  255.     for (i=0; i<crnt_cntr_pt_index; i++) {
  256.     cntr->coords[i].x = crnt_cntr[i * 2];
  257.     cntr->coords[i].y = crnt_cntr[i * 2 + 1];
  258.     cntr->coords[i].z = contour_level;
  259.     }
  260.     cntr->num_pts = crnt_cntr_pt_index;
  261.  
  262.     cntr->next = contour_list;
  263.     contour_list = cntr;
  264.      contour_list->isNewLevel = 0;
  265.  
  266.     crnt_cntr_pt_index = 0;
  267. }
  268.  
  269. /*
  270.  * Generates all contours by tracing the intersecting triangles.
  271.  */
  272. static void gen_contours(p_edges, z_level, x_min, x_max, y_min, y_max)
  273. struct edge_struct *p_edges;
  274. double z_level, x_min, x_max, y_min, y_max;
  275. {
  276.     int num_active,                        /* Number of edges marked ACTIVE. */
  277.     contour_kind;                /* One of OPEN_CONTOUR, CLOSED_CONTOUR. */
  278.     struct cntr_struct *p_cntr;
  279.  
  280.     num_active = update_all_edges(p_edges, z_level);           /* Do pass 1. */
  281.  
  282.     test_boundary = TRUE;        /* Start to look for contour on boundaries. */
  283.  
  284.     while (num_active > 0) {                                   /* Do Pass 2. */
  285.         /* Generate One contour (and update MumActive as needed): */
  286.     p_cntr = gen_one_contour(p_edges, z_level, &contour_kind, &num_active);
  287.     put_contour(p_cntr, z_level, x_min, x_max, y_min, y_max,
  288.                   contour_kind); /* Emit it in requested format. */
  289.     }
  290. }
  291.  
  292. /*
  293.  * Does pass 1, or marks the edges which are active (crosses this z_level)
  294.  * as ACTIVE, and the others as INACTIVE:
  295.  * Returns number of active edges (marked ACTIVE).
  296.  */
  297. static int update_all_edges(p_edges, z_level)
  298. struct edge_struct *p_edges;
  299. double z_level;
  300. {
  301.     int count = 0;
  302.  
  303.     while (p_edges) {
  304.     if (((p_edges -> vertex[0] -> Z >= z_level) &&
  305.          (p_edges -> vertex[1] -> Z <= z_level)) ||
  306.         ((p_edges -> vertex[1] -> Z >= z_level) &&
  307.          (p_edges -> vertex[0] -> Z <= z_level))) {
  308.         p_edges -> status = ACTIVE;
  309.         count++;
  310.     }
  311.     else p_edges -> status = INACTIVE;
  312.     p_edges = p_edges -> next;
  313.     }
  314.  
  315.     return count;
  316. }
  317.  
  318. /*
  319.  * Does pass 2, or find one complete contour out of the triangolation data base:
  320.  * Returns a pointer to the contour (as linked list), contour_kind is set to
  321.  * one of OPEN_CONTOUR, CLOSED_CONTOUR, and num_active is updated.
  322.  */
  323. static struct cntr_struct *gen_one_contour(p_edges, z_level, contour_kind,
  324.                                 num_active)
  325. struct edge_struct *p_edges;
  326. double z_level;
  327. int *contour_kind, *num_active;
  328. {
  329.     struct edge_struct *pe_temp;
  330.  
  331.     if (test_boundary) {    /* Look for something to start with on boundary: */
  332.     pe_temp = p_edges;
  333.     while (pe_temp) {
  334.         if ((pe_temp -> status == ACTIVE) && (pe_temp -> boundary)) break;
  335.         pe_temp = pe_temp -> next;
  336.     }
  337.     if (!pe_temp) test_boundary = FALSE;/* No more contours on boundary. */
  338.     else {
  339.         *contour_kind = OPEN_CONTOUR;
  340.         return trace_contour(pe_temp, z_level, num_active, *contour_kind);
  341.     }
  342.     }
  343.  
  344.     if (!test_boundary) {        /* Look for something to start with inside: */
  345.     pe_temp = p_edges;
  346.     while (pe_temp) {
  347.         if ((pe_temp -> status == ACTIVE) && (!(pe_temp -> boundary)))
  348.         break;
  349.         pe_temp = pe_temp -> next;
  350.     }
  351.     if (!pe_temp) {
  352.         *num_active = 0;
  353.         return NULL;
  354.     }
  355.     else {
  356.         *contour_kind = CLOSED_CONTOUR;
  357.         return trace_contour(pe_temp, z_level, num_active, *contour_kind);
  358.     }
  359.     }
  360.     return NULL;             /* We should never be here, but lint... */
  361. }
  362.  
  363. /*
  364.  * Search the data base along a contour starts at the edge pe_start until
  365.  * a boundary edge is detected or until we close the loop back to pe_start.
  366.  * Returns a linked list of all the points on the contour
  367.  * Also decreases num_active by the number of points on contour.
  368.  */
  369. static struct cntr_struct *trace_contour(pe_start, z_level, num_active,
  370.                                 contour_kind)
  371. struct edge_struct *pe_start;
  372. double z_level;
  373. int *num_active, contour_kind;
  374. {
  375.     int i, in_middle;       /* If TRUE the z_level is in the middle of edge. */
  376.     struct cntr_struct *p_cntr, *pc_tail;
  377.     struct edge_struct *p_edge = pe_start, *p_next_edge;
  378.     struct poly_struct *p_poly, *PLastpoly = NULL;
  379.  
  380.     /* Generate the header of the contour - the point on pe_start. */
  381.     if (contour_kind == OPEN_CONTOUR) pe_start -> status = INACTIVE;
  382.     (*num_active)--;
  383.     p_cntr = pc_tail = update_cntr_pt(pe_start, z_level, &in_middle);
  384.     if (!in_middle) {
  385.     return NULL;
  386.     }
  387.  
  388.     do {
  389.     /* Find polygon to continue (Not where we came from - PLastpoly): */
  390.     if (p_edge -> poly[0] == PLastpoly) p_poly = p_edge -> poly[1];
  391.     else p_poly = p_edge -> poly[0];
  392.     p_next_edge = NULL;          /* In case of error, remains NULL. */
  393.     for (i=0; i<3; i++)              /* Test the 3 edges of the polygon: */
  394.         if (p_poly -> edge[i] != p_edge)
  395.             if (p_poly -> edge[i] -> status == ACTIVE)
  396.             p_next_edge = p_poly -> edge[i];
  397.     if (!p_next_edge) {
  398.         pc_tail -> next = NULL;
  399.         free_contour(p_cntr);
  400.         return NULL;
  401.     }
  402.     p_edge = p_next_edge;
  403.     PLastpoly = p_poly;
  404.     p_edge -> status = INACTIVE;
  405.     (*num_active)--;
  406.     pc_tail -> next = update_cntr_pt(p_edge, z_level, &in_middle);
  407.     if (!in_middle) {
  408.         pc_tail -> next = NULL;
  409.         free_contour(p_cntr);
  410.         return NULL;
  411.     }
  412.         pc_tail = pc_tail -> next;
  413.     }
  414.     while ((pe_start != p_edge) && (!p_edge -> boundary));
  415.     pc_tail -> next = NULL;
  416.  
  417.     return p_cntr;
  418. }
  419.  
  420. /*
  421.  * Allocates one contour location and update it to to correct position
  422.  * according to z_level and edge p_edge. if z_level is found to be at
  423.  * one of the extreme points nothing is allocated (NULL is returned)
  424.  * and in_middle is set to FALSE.
  425.  */
  426. static struct cntr_struct *update_cntr_pt(p_edge, z_level, in_middle)
  427. struct edge_struct *p_edge;
  428. double z_level;
  429. int *in_middle;
  430. {
  431.     double t;
  432.     struct cntr_struct *p_cntr;
  433.  
  434.     t = (z_level - p_edge -> vertex[0] -> Z) /
  435.     (p_edge -> vertex[1] -> Z - p_edge -> vertex[0] -> Z);
  436.  
  437.     if (fuzzy_equal(t, 1.0) || fuzzy_equal(t, 0.0)) {
  438.         *in_middle = FALSE;
  439.         return NULL;
  440.     }
  441.     else {
  442.     *in_middle = TRUE;
  443.     p_cntr = (struct cntr_struct *) alloc((unsigned long)sizeof(struct cntr_struct),
  444.                             "contour cntr_struct");
  445.     p_cntr -> X = p_edge -> vertex[1] -> X * t +
  446.              p_edge -> vertex[0] -> X * (1-t);
  447.     p_cntr -> Y = p_edge -> vertex[1] -> Y * t +
  448.              p_edge -> vertex[0] -> Y * (1-t);
  449.     return p_cntr;
  450.     }
  451. }
  452.  
  453. /*
  454.  * Simple routine to decide if two real values are equal by simply
  455.  * calculating the relative/absolute error between them (< EPSILON).
  456.  */
  457. static int fuzzy_equal(x, y)
  458. double x, y;
  459. {
  460.     if (abs(x) > EPSILON)            /* Calculate relative error: */
  461.         return (abs((x - y) / x) < EPSILON);
  462.     else                    /* Calculate absolute error: */
  463.     return (abs(x - y) < EPSILON);
  464. }
  465.  
  466. /*
  467.  * Generate the triangles.
  468.  * Returns the lists (vrtxs edges & polys) via pointers to their heads.
  469.  */
  470. static void gen_triangle(num_isolines, iso_lines, p_polys, p_edges,
  471.     p_vrts, x_min, y_min, z_min, x_max, y_max, z_max)
  472. int num_isolines;
  473. struct iso_curve *iso_lines;
  474. struct poly_struct **p_polys;
  475. struct edge_struct **p_edges;
  476. struct vrtx_struct **p_vrts;
  477. double *x_min, *y_min, *z_min, *x_max, *y_max, *z_max;
  478. {
  479.     int i, grid_x_max = iso_lines->p_count;
  480.     struct vrtx_struct *p_vrtx1, *p_vrtx2, *pv_temp;
  481.     struct edge_struct *p_edge1, *p_edge2, *pe_tail1, *pe_tail2, *pe_temp,
  482.               *p_edge_middle, *pe_m_tail;
  483.     struct poly_struct *p_poly, *pp_tail;
  484.  
  485.     *p_polys = NULL;
  486.     *p_edges = NULL;
  487.     *p_vrts = NULL;
  488.     *z_min = INFINITY;
  489.     *y_min = INFINITY;
  490.     *x_min = INFINITY;
  491.     *z_max = -INFINITY;
  492.     *y_max = -INFINITY;
  493.     *x_max = -INFINITY;
  494.  
  495.     /* Read 1st row. */
  496.     p_vrtx1 = gen_vertices(grid_x_max, iso_lines->points,
  497.                x_min, y_min, z_min, x_max, y_max, z_max);
  498.     *p_vrts = p_vrtx1;
  499.     /* Gen. its edges.*/
  500.     pe_temp = p_edge1 = gen_edges(grid_x_max, p_vrtx1, &pe_tail1);
  501.     for (i = 1; i < grid_x_max; i++) {/* Mark one side of edges as boundary. */
  502.     pe_temp -> poly[1] = NULL;
  503.     pe_temp = pe_temp -> next;
  504.     }
  505.     for (i = 1; i < num_isolines; i++) { /* Read next column and gen. polys. */
  506.     iso_lines = iso_lines->next;
  507.         /* Get row into list. */
  508.         p_vrtx2 = gen_vertices(grid_x_max, iso_lines->points,
  509.                    x_min, y_min, z_min, x_max, y_max, z_max);
  510.         /* Generate its edges. */
  511.         p_edge2 = gen_edges(grid_x_max, p_vrtx2, &pe_tail2);
  512.     /* Generate edges from one vertex list to the other one: */
  513.     p_edge_middle = gen_edges_middle(grid_x_max, p_vrtx1, p_vrtx2,
  514.                                  &pe_m_tail);
  515.  
  516.     /* Now we can generate the polygons themselves (triangles). */
  517.     p_poly = gen_polys(grid_x_max, p_edge1, p_edge_middle, p_edge2,
  518.                                  &pp_tail);
  519.         pe_tail1 -> next = (*p_edges);      /* Chain new edges to main list. */
  520.         pe_m_tail -> next = p_edge1;
  521.     *p_edges = p_edge_middle;
  522.     pe_tail1 = pe_tail2;
  523.     p_edge1 = p_edge2;
  524.  
  525.     pv_temp = p_vrtx2;
  526.     while (pv_temp -> next) pv_temp = pv_temp -> next;
  527.     pv_temp -> next = *p_vrts;
  528.     *p_vrts = p_vrtx1 = p_vrtx2;
  529.  
  530.         pp_tail -> next = (*p_polys);       /* Chain new polys to main list. */
  531.     *p_polys = p_poly;
  532.     }
  533.  
  534.     pe_temp = p_edge1;
  535.     for (i = 1; i < grid_x_max; i++) {/* Mark one side of edges as boundary. */
  536.     pe_temp -> poly[0] = NULL;
  537.     pe_temp = pe_temp -> next;
  538.     }
  539.  
  540.     pe_tail1 -> next = (*p_edges);    /* Chain last edges list to main list. */
  541.     *p_edges = p_edge1;
  542.  
  543.     /* Update the boundary flag, saved in each edge, and update indexes: */
  544.     pe_temp = (*p_edges);
  545.     i = 1;
  546.  
  547.     while (pe_temp) {
  548.     pe_temp -> boundary = (!(pe_temp -> poly[0])) ||
  549.                   (!(pe_temp -> poly[1]));
  550.     pe_temp = pe_temp -> next;
  551.     }
  552. }
  553.  
  554. /*
  555.  * Handles grid_x_max 3D points (One row) and generate linked list for them.
  556.  */
  557. static struct vrtx_struct *gen_vertices(grid_x_max, points,
  558.                       x_min, y_min, z_min, x_max, y_max, z_max)
  559. int grid_x_max;
  560. struct coordinate GPHUGE *points;
  561. double *x_min, *y_min, *z_min, *x_max, *y_max, *z_max;
  562. {
  563.     int i;
  564.     struct vrtx_struct *p_vrtx, *pv_tail, *pv_temp;
  565.  
  566.     for (i=0; i<grid_x_max; i++) {/* Get a point and generate the structure. */
  567.         pv_temp = (struct vrtx_struct *) alloc((unsigned long)sizeof(struct vrtx_struct),
  568.                         "contour vertex");
  569.     pv_temp -> X = points[i].x;
  570.     pv_temp -> Y = points[i].y;
  571.     pv_temp -> Z = points[i].z;
  572.  
  573.     if (pv_temp -> X > *x_max) *x_max = pv_temp -> X; /* Update min/max. */
  574.     if (pv_temp -> Y > *y_max) *y_max = pv_temp -> Y;
  575.     if (pv_temp -> Z > *z_max) *z_max = pv_temp -> Z;
  576.     if (pv_temp -> X < *x_min) *x_min = pv_temp -> X;
  577.     if (pv_temp -> Y < *y_min) *y_min = pv_temp -> Y;
  578.     if (pv_temp -> Z < *z_min) *z_min = pv_temp -> Z;
  579.  
  580.     if (i == 0)                              /* First vertex in row: */
  581.         p_vrtx = pv_tail = pv_temp;
  582.     else {
  583.         pv_tail -> next = pv_temp;   /* Stick new record as last one. */
  584.         pv_tail = pv_tail -> next;    /* And continue to last record. */
  585.     }
  586.     }
  587.     pv_tail -> next = NULL;
  588.  
  589.     return p_vrtx;
  590. }
  591.  
  592. /*
  593.  * Combines N vertices in pair to form N-1 edges.
  594.  * Returns pointer to the edge list (pe_tail will point on last edge in list).
  595.  */
  596. static struct edge_struct *gen_edges(grid_x_max, p_vrtx, pe_tail)
  597. int grid_x_max;
  598. struct vrtx_struct *p_vrtx;
  599. struct edge_struct **pe_tail;
  600. {
  601.     int i;
  602.     struct edge_struct *p_edge, *pe_temp;
  603.  
  604.     for (i=0; i<grid_x_max-1; i++) {         /* Generate grid_x_max-1 edges: */
  605.     pe_temp = (struct edge_struct *) alloc((unsigned long)sizeof(struct edge_struct),
  606.                         "contour edge");
  607.     pe_temp -> vertex[0] = p_vrtx;              /* First vertex of edge. */
  608.     p_vrtx = p_vrtx -> next;                     /* Skip to next vertex. */
  609.     pe_temp -> vertex[1] = p_vrtx;             /* Second vertex of edge. */
  610.         if (i == 0)                                    /* First edge in row: */
  611.         p_edge = (*pe_tail) = pe_temp;
  612.     else {
  613.         (*pe_tail) -> next = pe_temp;   /* Stick new record as last one. */
  614.         *pe_tail = (*pe_tail) -> next;   /* And continue to last record. */
  615.      }
  616.     }
  617.     (*pe_tail) -> next = NULL;
  618.  
  619.     return p_edge;
  620. }
  621.  
  622. /*
  623.  * Combines 2 lists of N vertices each into edge list:
  624.  * The dots (.) are the vertices list, and the              .  .  .  .
  625.  *  edges generated are alternations of vertical edges      |\ |\ |\ |
  626.  *  (|) and diagonal ones (\).                              | \| \| \|
  627.  *  A pointer to edge list (alternate | , \) is returned    .  .  .  .
  628.  * Note this list will have (2*grid_x_max-1) edges (pe_tail points on last
  629.  * record).
  630.  */
  631. static struct edge_struct *gen_edges_middle(grid_x_max, p_vrtx1, p_vrtx2,
  632.                                 pe_tail)
  633. int grid_x_max;
  634. struct vrtx_struct *p_vrtx1, *p_vrtx2;
  635. struct edge_struct **pe_tail;
  636. {
  637.     int i;
  638.     struct edge_struct *p_edge, *pe_temp;
  639.  
  640.     /* Gen first (|). */
  641.     pe_temp = (struct edge_struct *) alloc((unsigned long)sizeof(struct edge_struct),
  642.                             "contour edge");
  643.     pe_temp -> vertex[0] = p_vrtx2;                 /* First vertex of edge. */
  644.     pe_temp -> vertex[1] = p_vrtx1;                /* Second vertex of edge. */
  645.     p_edge = (*pe_tail) = pe_temp;
  646.  
  647.     /* Advance in vrtx list grid_x_max-1 times, and gen. 2 edges /| for each.*/
  648.     for (i=0; i<grid_x_max-1; i++) {
  649.     /* The / edge. */
  650.     pe_temp = (struct edge_struct *) alloc((unsigned long)sizeof(struct edge_struct),
  651.                             "contour edge");
  652.     pe_temp -> vertex[0] = p_vrtx1;             /* First vertex of edge. */
  653.     pe_temp -> vertex[1] = p_vrtx2 -> next;    /* Second vertex of edge. */
  654.         (*pe_tail) -> next = pe_temp;       /* Stick new record as last one. */
  655.     *pe_tail = (*pe_tail) -> next;       /* And continue to last record. */
  656.  
  657.     /* The | edge. */
  658.     pe_temp = (struct edge_struct *) alloc((unsigned long)sizeof(struct edge_struct),
  659.                             "contour edge");
  660.     pe_temp -> vertex[0] = p_vrtx2 -> next;     /* First vertex of edge. */
  661.     pe_temp -> vertex[1] = p_vrtx1 -> next;    /* Second vertex of edge. */
  662.         (*pe_tail) -> next = pe_temp;       /* Stick new record as last one. */
  663.     *pe_tail = (*pe_tail) -> next;       /* And continue to last record. */
  664.  
  665.         p_vrtx1 = p_vrtx1 -> next;   /* Skip to next vertices in both lists. */
  666.         p_vrtx2 = p_vrtx2 -> next;
  667.     }
  668.     (*pe_tail) -> next = NULL;
  669.  
  670.     return p_edge;
  671. }
  672.  
  673. /*
  674.  * Combines 3 lists of edges into triangles:
  675.  * 1. p_edge1: Top horizontal edge list:        -----------------------
  676.  * 2. p_edge_middge: middle edge list:         |\  |\  |\  |\  |\  |\  |
  677.  *                                             |  \|  \|  \|  \|  \|  \|
  678.  * 3. p_edge2: Bottom horizontal edge list:     -----------------------
  679.  * Note that p_edge1/2 lists has grid_x_max-1 edges, while p_edge_middle has
  680.  * (2*grid_x_max-1) edges.
  681.  * The routine simple scans the two list    Upper 1         Lower
  682.  * and generate two triangle upper one        ----         | \
  683.  * and lower one from the lists:             0\   |2      0|   \1
  684.  * (Nums. are edges order in polys)             \ |         ----
  685.  * The routine returns a pointer to a                         2
  686.  * polygon list (pp_tail points on last polygon).          1
  687.  *                                                   -----------
  688.  * In addition, the edge lists are updated -        | \   0     |
  689.  * each edge has two pointers on the two            |   \       |
  690.  * (one active if boundary) polygons which         0|1   0\1   0|1
  691.  * uses it. These two pointer to polygons           |       \   |
  692.  * are named: poly[0], poly[1]. The diagram         |    1    \ |
  693.  * on the right show how they are used for the       -----------
  694.  * upper and lower polygons.                             0
  695.  */
  696. static struct poly_struct *gen_polys(grid_x_max, p_edge1, p_edge_middle,
  697.                             p_edge2, pp_tail)
  698. int grid_x_max;
  699. struct edge_struct *p_edge1, *p_edge_middle, *p_edge2;
  700. struct poly_struct **pp_tail;
  701. {
  702.     int i;
  703.     struct poly_struct *p_poly, *pp_temp;
  704.  
  705.     p_edge_middle -> poly[0] = NULL;                /* Its boundary! */
  706.  
  707.     /* Advance in vrtx list grid_x_max-1 times, and gen. 2 polys for each. */
  708.     for (i=0; i<grid_x_max-1; i++) {
  709.     /* The Upper. */
  710.     pp_temp = (struct poly_struct *) alloc((unsigned long)sizeof(struct poly_struct),
  711.                             "contour poly");
  712.     /* Now update polys about its edges, and edges about the polygon. */
  713.     pp_temp -> edge[0] = p_edge_middle -> next;
  714.     p_edge_middle -> next -> poly[1] = pp_temp;
  715.     pp_temp -> edge[1] = p_edge1;
  716.     p_edge1 -> poly[0] = pp_temp;
  717.     pp_temp -> edge[2] = p_edge_middle -> next -> next;
  718.     p_edge_middle -> next -> next -> poly[0] = pp_temp;
  719.     if (i == 0)                   /* Its first one in list: */
  720.         p_poly = (*pp_tail) = pp_temp;
  721.     else {
  722.         (*pp_tail) -> next = pp_temp;
  723.         *pp_tail = (*pp_tail) -> next;
  724.     }
  725.  
  726.     /* The Lower. */
  727.     pp_temp = (struct poly_struct *) alloc((unsigned long)sizeof(struct poly_struct),
  728.                             "contour poly");
  729.     /* Now update polys about its edges, and edges about the polygon. */
  730.     pp_temp -> edge[0] = p_edge_middle;
  731.     p_edge_middle -> poly[1] = pp_temp;
  732.     pp_temp -> edge[1] = p_edge_middle -> next;
  733.     p_edge_middle -> next -> poly[0] = pp_temp;
  734.     pp_temp -> edge[2] = p_edge2;
  735.     p_edge2 -> poly[1] = pp_temp;
  736.     (*pp_tail) -> next = pp_temp;
  737.     *pp_tail = (*pp_tail) -> next;
  738.  
  739.         p_edge1 = p_edge1 -> next;
  740.         p_edge2 = p_edge2 -> next;
  741.         p_edge_middle = p_edge_middle -> next -> next;
  742.     }
  743.     p_edge_middle -> poly[1] = NULL;                /* Its boundary! */
  744.     (*pp_tail) -> next = NULL;
  745.  
  746.     return p_poly;
  747. }
  748.  
  749. /*
  750.  * Calls the (hopefully) desired interpolation/approximation routine.
  751.  */
  752. static void put_contour(p_cntr, z_level, x_min, x_max, y_min, y_max, contr_kind)
  753. struct cntr_struct *p_cntr;
  754. double z_level, x_min, x_max, y_min, y_max;
  755. int contr_kind;
  756. {
  757.     if (!p_cntr) return;            /* Nothing to do if it is empty contour. */
  758.  
  759.     switch (interp_kind) {
  760.     case INTERP_NOTHING:              /* No interpolation/approximation. */
  761.         put_contour_nothing(p_cntr);
  762.         break;
  763.     case INTERP_CUBIC:                    /* Cubic spline interpolation. */
  764.         put_contour_cubic(p_cntr, z_level, x_min, x_max, y_min, y_max,
  765.                                 contr_kind);
  766.         break;
  767.     case APPROX_BSPLINE:                       /* Bspline approximation. */
  768.         put_contour_bspline(p_cntr, z_level, x_min, x_max, y_min, y_max,
  769.                                     contr_kind);
  770.         break;
  771.     }
  772.  
  773.     free_contour(p_cntr);
  774. }
  775.  
  776. /*
  777.  * Simply puts contour coordinates in order with no interpolation or
  778.  * approximation.
  779.  */
  780. static put_contour_nothing(p_cntr)
  781. struct cntr_struct *p_cntr;
  782. {
  783.     while (p_cntr) {
  784.     add_cntr_point(p_cntr -> X, p_cntr -> Y);
  785.     p_cntr = p_cntr -> next;
  786.     }
  787.     end_crnt_cntr();
  788. }
  789.  
  790. /*
  791.  * Find Complete Cubic Spline Interpolation.
  792.  */
  793. static put_contour_cubic(p_cntr, z_level, x_min, x_max, y_min, y_max,
  794.                                  contr_kind)
  795. struct cntr_struct *p_cntr;
  796. double z_level, x_min, x_max, y_min, y_max;
  797. int contr_kind;
  798. {
  799.     int num_pts, i;
  800.     double tx1, ty1, tx2, ty2;                    /* Tangents at end points. */
  801.     struct cntr_struct *pc_temp;
  802.  
  803.     num_pts = count_contour(p_cntr);         /* Number of points in contour. */
  804.  
  805.     if (num_pts > 2) {  /* Take into account 3 points in tangent estimation. */
  806.     calc_tangent(3, p_cntr -> X, p_cntr -> next -> X,
  807.             p_cntr -> next -> next -> X,
  808.             p_cntr -> Y, p_cntr -> next -> Y,
  809.             p_cntr -> next -> next -> Y, &tx1, &ty1);
  810.     pc_temp = p_cntr;
  811.     for (i=3; i<num_pts; i++) pc_temp = pc_temp -> next;/* Go to the end.*/
  812.     calc_tangent(3, pc_temp -> next -> next -> X,
  813.              pc_temp -> next -> X, pc_temp -> X,
  814.             pc_temp -> next -> next -> Y,
  815.             pc_temp -> next -> Y, pc_temp -> Y, &tx2, &ty2);
  816.         tx2 = (-tx2);   /* Inverse the vector as we need opposite direction. */
  817.         ty2 = (-ty2);
  818.     }
  819.     /* If following (num_pts > 1) is TRUE then exactly 2 points in contour.  */
  820.     else if (num_pts > 1) {/* Take into account 2 points in tangent estimat. */
  821.     calc_tangent(2, p_cntr -> X, p_cntr -> next -> X, 0.0,
  822.             p_cntr -> Y, p_cntr -> next -> Y, 0.0, &tx1, &ty1);
  823.     calc_tangent(2, p_cntr -> next -> X, p_cntr -> X, 0.0,
  824.             p_cntr -> next -> Y, p_cntr -> Y, 0.0, &tx2, &ty2);
  825.         tx2 = (-tx2);   /* Inverse the vector as we need opposite direction. */
  826.         ty2 = (-ty2);
  827.     }
  828.     else return(0);            /* Only one point (???) - ignore it. */
  829.  
  830.     switch (contr_kind) {
  831.     case OPEN_CONTOUR:
  832.         break;
  833.     case CLOSED_CONTOUR:
  834.         tx1 = tx2 = (tx1 + tx2) / 2.0;         /* Make tangents equal. */
  835.         ty1 = ty2 = (ty1 + ty2) / 2.0;
  836.         break;
  837.     }
  838.     complete_spline_interp(p_cntr, num_pts, 0.0, 1.0, tx1, ty1, tx2, ty2);
  839.     end_crnt_cntr();
  840. }
  841.  
  842. /*
  843.  * Find Bspline approximation for this data set.
  844.  * Uses global variable num_approx_pts to determine number of samples per
  845.  * interval, where the knot vector intervals are assumed to be uniform, and
  846.  * Global variable bspline_order for the order of Bspline to use.
  847.  */
  848. static put_contour_bspline(p_cntr, z_level, x_min, x_max, y_min, y_max,
  849.                                 contr_kind)
  850. struct cntr_struct *p_cntr;
  851. double z_level, x_min, x_max,  y_min, y_max;
  852. int contr_kind;
  853. {
  854.     int num_pts, i, order = bspline_order;
  855.     struct cntr_struct *pc_temp;
  856.  
  857.     num_pts = count_contour(p_cntr);         /* Number of points in contour. */
  858.     if (num_pts < 2) return(0);     /* Can't do nothing if empty or one points! */
  859.     /* Order must be less than number of points in curve - fix it if needed. */
  860.     if (order > num_pts - 1) order = num_pts - 1;
  861.  
  862.     gen_bspline_approx(p_cntr, num_pts, order, contr_kind);
  863.     end_crnt_cntr();
  864. }
  865.  
  866. /*
  867.  * Estimate the tangents according to the n last points where n might be
  868.  * 2 or 3 (if 2 onlt x1, x2).
  869.  */
  870. static calc_tangent(n, x1, x2, x3, y1, y2, y3, tx, ty)
  871. int n;
  872. double x1, x2, x3, y1, y2, y3, *tx, *ty;
  873. {
  874.     double v1[2], v2[2], v1_magnitude, v2_magnitude;
  875.  
  876.     switch (n) {
  877.     case 2:
  878.         *tx = (x2 - x1) * 0.3;
  879.         *ty = (y2 - y1) * 0.3;
  880.         break;
  881.     case 3:
  882.         v1[0] = x2 - x1;   v1[1] = y2 - y1;
  883.         v2[0] = x3 - x2;   v2[1] = y3 - y2;
  884.         v1_magnitude = sqrt(sqr(v1[0]) + sqr(v1[1]));
  885.         v2_magnitude = sqrt(sqr(v2[0]) + sqr(v2[1]));
  886.         *tx = (v1[0] / v1_magnitude) - (v2[0] / v2_magnitude) * 0.1;
  887.         *tx *= v1_magnitude * 0.1;  /* Make tangent less than magnitude. */
  888.         *ty = (v1[1] / v1_magnitude) - (v2[1] / v2_magnitude) * 0.1;
  889.         *ty *= v1_magnitude * 0.1;  /* Make tangent less than magnitude. */
  890.         break;
  891.     default:                       /* Should not happen! */
  892.         (*ty) = 0.1;
  893.         *tx = 0.1;
  894.         break;
  895.     }
  896. }
  897.  
  898. /*
  899.  * Free all elements in the contour list.
  900.  */
  901. static void free_contour(p_cntr)
  902. struct cntr_struct *p_cntr;
  903. {
  904.     struct cntr_struct *pc_temp;
  905.  
  906.     while (p_cntr) {
  907.     pc_temp = p_cntr;
  908.     p_cntr = p_cntr -> next;
  909.     free((char *) pc_temp);
  910.     }
  911. }
  912.  
  913. /*
  914.  * Counts number of points in contour.
  915.  */
  916. static int count_contour(p_cntr)
  917. struct cntr_struct *p_cntr;
  918. {
  919.     int count = 0;
  920.  
  921.     while (p_cntr) {
  922.     count++;
  923.     p_cntr = p_cntr -> next;
  924.     }
  925.     return count;
  926. }
  927.  
  928. /*
  929.  * Interpolate given point list (defined via p_cntr) using Complete
  930.  * Spline interpolation.
  931.  */
  932. static complete_spline_interp(p_cntr, n, t_min, t_max, tx1, ty1, tx2, ty2)
  933. struct cntr_struct *p_cntr;
  934. int n;
  935. double t_min, t_max, tx1, ty1, tx2, ty2;
  936. {
  937.     double dt, *tangents_x, *tangents_y;
  938.     int i;
  939.  
  940.     tangents_x = (double *) alloc((unsigned long) (sizeof(double) * n),
  941.                         "contour c_s_intr");
  942.     tangents_y = (double *) alloc((unsigned long) (sizeof(double) * n),
  943.                         "contour c_s_intr");
  944.  
  945.     if (n > 1) prepare_spline_interp(tangents_x, tangents_y, p_cntr, n,
  946.                     t_min, t_max, tx1, ty1, tx2, ty2);
  947.     else {
  948.     free((char *) tangents_x);
  949.     free((char *) tangents_y);
  950.     return(0);
  951.     }
  952.  
  953.     dt = (t_max-t_min)/(n-1);
  954.  
  955.     add_cntr_point(p_cntr -> X, p_cntr -> Y);           /* First point. */
  956.  
  957.     for (i=0; i<n-1; i++) {
  958.         hermit_interp(p_cntr -> X, p_cntr -> Y,
  959.                      tangents_x[i], tangents_y[i],
  960.              p_cntr -> next -> X, p_cntr -> next -> Y,
  961.                      tangents_x[i+1], tangents_y[i+1], dt);
  962.  
  963.         p_cntr = p_cntr -> next;
  964.     }
  965.  
  966.     free((char *) tangents_x);
  967.     free((char *) tangents_y);
  968. }
  969.  
  970. /*
  971.  * Routine to calculate intermidiate value of the Hermit Blending function:
  972.  * This routine should be called only ONCE at the beginning of the program.
  973.  */
  974. static calc_hermit_table()
  975. {
  976.     int i;
  977.     double t, dt;
  978.  
  979.     hermit_table = (table_entry *) alloc ((unsigned long) (sizeof(table_entry) *
  980.                         (num_approx_pts + 1)),
  981.                         "contour hermit table");
  982.     t = 0;
  983.     dt = 1.0/num_approx_pts;
  984.     for (i=0; i<=num_approx_pts; i++) {
  985.         hermit_table[i][0] = (t-1)*(t-1)*(2*t+1);             /* h00. */
  986.         hermit_table[i][1] = t*t*(-2*t+3);                 /* h10. */
  987.         hermit_table[i][2] = t*(t-1)*(t-1);                 /* h01. */
  988.         hermit_table[i][3] = t*t*(t-1);                     /* h11. */
  989.         t = t + dt;
  990.     }
  991. }
  992.  
  993. /*
  994.  * Routine to generate an hermit interpolation between two points given as
  995.  * two InterpStruct structures. Assume hermit_table is already calculated.
  996.  * Currently the points generated are printed to stdout as two reals (X, Y).
  997.  */
  998. static hermit_interp(x1, y1, tx1, ty1, x2, y2, tx2, ty2, dt)
  999. double x1, y1, tx1, ty1, x2, y2, tx2, ty2, dt;
  1000. {
  1001.     int i;
  1002.     double x, y, vec_size, tang_size;
  1003.  
  1004.     tx1 *= dt;  ty1 *= dt; /* Normalize the tangents according to param. t.  */
  1005.     tx2 *= dt;  ty2 *= dt;
  1006.  
  1007.     /* Normalize the tangents so that their magnitude will be 1/3 of the     */
  1008.     /* segment length. This tumb rule guaranteed no cusps or loops!          */
  1009.     /* Note that this normalization keeps continuity to be G1 (but not C1).  */
  1010.     vec_size = sqrt(sqr(x1 - x2) + sqr(y2 - y1));
  1011.     tang_size = sqrt(sqr(tx1) + sqr(ty1));                  /* Normalize T1. */
  1012.     if (tang_size * 3 > vec_size) {
  1013.     tx1 *= vec_size / (tang_size * 3);
  1014.     ty1 *= vec_size / (tang_size * 3);
  1015.     }
  1016.     tang_size = sqrt(sqr(tx2) + sqr(ty2));                  /* Normalize T2. */
  1017.     if (tang_size * 3 > vec_size) {
  1018.     tx2 *= vec_size / (tang_size * 3);
  1019.     ty2 *= vec_size / (tang_size * 3);
  1020.     }
  1021.  
  1022.     for (i=1; i<=num_approx_pts; i++) {      /* Note we start from 1 - first */
  1023.         x = hermit_table[i][0] * x1 +       /* point is not printed as it is */
  1024.             hermit_table[i][1] * x2 +   /* redundent (last on last section). */
  1025.             hermit_table[i][2] * tx1 +
  1026.             hermit_table[i][3] * tx2;
  1027.         y = hermit_table[i][0] * y1 +
  1028.             hermit_table[i][1] * y2 +
  1029.             hermit_table[i][2] * ty1 +
  1030.             hermit_table[i][3] * ty2;
  1031.     add_cntr_point(x, y);
  1032.     }
  1033. }
  1034.  
  1035. /*
  1036.  * Routine to Set up the 3*N mat for solve_tri_diag routine used in the
  1037.  * Complete Spline Interpolation. Returns TRUE of calc O.K.
  1038.  * Gets the points list in p_cntr (Of length n) and with tangent vectors tx1,
  1039.  * ty1 at starting point and tx2, ty2 and end point.
  1040.  */
  1041. static prepare_spline_interp(tangents_x, tangents_y, p_cntr, n, t_min, t_max,
  1042.                tx1, ty1, tx2, ty2)
  1043. double tangents_x[], tangents_y[];
  1044. struct cntr_struct *p_cntr;
  1045. int n;
  1046. double t_min, t_max, tx1, ty1, tx2, ty2;
  1047. {
  1048.     int i;
  1049.     double *r, t, dt;
  1050.     tri_diag *m;           /* The tri-diagonal matrix is saved here. */
  1051.     struct cntr_struct *p;
  1052.  
  1053.     m = (tri_diag *) alloc((unsigned long) (sizeof(tri_diag) * n),
  1054.                         "contour tri_diag");
  1055.     r = (double *) alloc((unsigned long) (sizeof(double) * n),
  1056.                         "contour tri_diag2");
  1057.     n--;
  1058.  
  1059.     p = p_cntr;
  1060.     m[0][0] = 0.0;    m[0][1] = 1.0;    m[0][2] = 0.0;
  1061.     m[n][0] = 0.0;    m[n][1] = 1.0;    m[n][2] = 0.0;
  1062.     r[0] = tx1;                           /* Set start tangent. */
  1063.     r[n] = tx2;                         /* Set end tangent. */
  1064.     t = t_min;
  1065.     dt = (t_max-t_min)/n;
  1066.     for (i=1; i<n; i++) {
  1067.        t = t + dt;
  1068.        m[i][0] = dt;
  1069.        m[i][2] = dt;
  1070.        m[i][1] = 2 * (m[i][0] + m[i][2]);
  1071.        r[i] = m[i][0] * ((p -> next -> X) - (p -> X)) / m[i][2]
  1072.             + m[i][2] * ((p -> next -> next -> X) - 
  1073.                          (p -> next -> X)) / m[i][0];
  1074.        r[i] *= 3.0;
  1075.        p = p -> next;
  1076.     }
  1077.  
  1078.     if (!solve_tri_diag(m, r, tangents_x, n+1)) { /* Find the X(t) tangents. */
  1079.         free((char *) m);
  1080.         free((char *) r);
  1081.     int_error("Cannt interpolate X using complete splines", NO_CARET);
  1082.     }
  1083.  
  1084.     p = p_cntr;
  1085.     m[0][0] = 0.0;    m[0][1] = 1.0;    m[0][2] = 0.0;
  1086.     m[n][0] = 0.0;    m[n][1] = 1.0;    m[n][2] = 0.0;
  1087.     r[0] = ty1;                           /* Set start tangent. */
  1088.     r[n] = ty2;                         /* Set end tangent. */
  1089.     t = t_min;
  1090.     dt = (t_max-t_min)/n;
  1091.     for (i=1; i<n; i++) {
  1092.        t = t + dt;
  1093.        m[i][0] = dt;
  1094.        m[i][2] = dt;
  1095.        m[i][1] = 2 * (m[i][0] + m[i][2]);
  1096.        r[i] = m[i][0] * ((p -> next -> Y) - (p -> Y)) / m[i][2]
  1097.             + m[i][2] * ((p -> next -> next -> Y) -
  1098.                          (p -> next -> Y)) / m[i][0];
  1099.        r[i] *= 3.0;
  1100.        p = p -> next;
  1101.     }
  1102.  
  1103.     if (!solve_tri_diag(m, r, tangents_y, n+1)) { /* Find the Y(t) tangents. */
  1104.         free((char *) m);
  1105.         free((char *) r);
  1106.     int_error("Cannt interpolate Y using complete splines", NO_CARET);
  1107.     }
  1108.     free((char *) m);
  1109.     free((char *) r);
  1110. }
  1111.  
  1112. /*
  1113.  * Solve tri diagonal linear system equation. The tri diagonal matrix is
  1114.  * defined via matrix M, right side is r, and solution X i.e. M * X = R.
  1115.  * Size of system given in n. Return TRUE if solution exist.
  1116.  */
  1117. static int solve_tri_diag(m, r, x, n)
  1118. tri_diag m[];
  1119. double r[], x[];
  1120. int n;
  1121. {
  1122.     int i;
  1123.     double t;
  1124.  
  1125.     for (i=1; i<n; i++) {   /* Eliminate element m[i][i-1] (lower diagonal). */
  1126.     if (m[i-1][1] == 0) return FALSE;
  1127.     t = m[i][0] / m[i-1][1];        /* Find ratio between the two lines. */
  1128.     m[i][0] = m[i][0] - m[i-1][1] * t;
  1129.     m[i][1] = m[i][1] - m[i-1][2] * t;
  1130.     r[i] = r[i] - r[i-1] * t;
  1131.     }
  1132.     /* Now do back subtitution - update the solution vector X: */
  1133.     if (m[n-1][1] == 0) return FALSE;
  1134.     x[n-1] = r[n-1] / m[n-1][1];               /* Find last element. */
  1135.     for (i=n-2; i>=0; i--) {
  1136.     if (m[i][1] == 0) return FALSE;
  1137.     x[i] = (r[i] - x[i+1] * m[i][2]) / m[i][1];
  1138.     }
  1139.     return TRUE;
  1140. }
  1141.  
  1142. /*
  1143.  * Generate a Bspline curve defined by all the points given in linked list p:
  1144.  * Algorithm: using deBoor algorithm
  1145.  * Note: if Curvekind is OPEN_CONTOUR than Open end knot vector is assumed,
  1146.  *       else (CLOSED_CONTOUR) Float end knot vector is assumed.
  1147.  * It is assumed that num_of_points is at list 2, and order of Bspline is less
  1148.  * than num_of_points!
  1149.  */
  1150. static gen_bspline_approx(p_cntr, num_of_points, order, contour_kind)
  1151. struct cntr_struct *p_cntr;
  1152. int num_of_points, order, contour_kind;
  1153. {
  1154.     int i, knot_index = 0, pts_count = 1;
  1155.     double dt, t, next_t, t_min, t_max, x, y;
  1156.     struct cntr_struct *pc_temp = p_cntr, *pc_tail;
  1157.  
  1158.     /* If the contour is Closed one we must update few things:               */
  1159.     /* 1. Make the list temporary circular, so we can close the contour.     */
  1160.     /* 2. Update num_of_points - increase it by "order-1" so contour will be */
  1161.     /*    closed. This will evaluate order more sections to close it!        */
  1162.     if (contour_kind == CLOSED_CONTOUR) {
  1163.     pc_tail = p_cntr;
  1164.     while (pc_tail -> next) pc_tail = pc_tail -> next;/* Find last point.*/
  1165.     pc_tail -> next = p_cntr;   /* Close contour list - make it circular.*/
  1166.     num_of_points += order;
  1167.     }
  1168.  
  1169.     /* Find first (t_min) and last (t_max) t value to eval: */
  1170.     t = t_min = fetch_knot(contour_kind, num_of_points, order, order);
  1171.     t_max = fetch_knot(contour_kind, num_of_points, order, num_of_points);
  1172.     next_t = t_min + 1.0;
  1173.     knot_index = order;
  1174.     dt = 1.0/num_approx_pts;            /* Number of points per one section. */
  1175.  
  1176.  
  1177.     while (t<t_max) {
  1178.     if (t > next_t) {
  1179.         pc_temp = pc_temp -> next;     /* Next order ctrl. pt. to blend. */
  1180.             knot_index++;
  1181.         next_t += 1.0;
  1182.     }
  1183.         eval_bspline(t, pc_temp, num_of_points, order, knot_index,
  1184.                         contour_kind, &x, &y);   /* Next pt. */
  1185.     add_cntr_point(x, y);
  1186.     pts_count++;
  1187.     /* As we might have some real number round off problems we must      */
  1188.     /* test if we dont produce too many points here...                   */
  1189.     if (pts_count + 1 == num_approx_pts * (num_of_points - order) + 1)
  1190.             break;
  1191.         t += dt;
  1192.     }
  1193.  
  1194.     eval_bspline(t_max - EPSILON, pc_temp, num_of_points, order, knot_index,
  1195.         contour_kind, &x, &y);
  1196.     /* If from round off errors we need more than one last point: */
  1197.     for (i=pts_count; i<num_approx_pts * (num_of_points - order) + 1; i++)
  1198.     add_cntr_point(x, y);                /* Complete the contour. */
  1199.  
  1200.     if (contour_kind == CLOSED_CONTOUR)     /* Update list - un-circular it. */
  1201.     pc_tail -> next = NULL;
  1202. }
  1203.  
  1204. /*
  1205.  * The recursive routine to evaluate the B-spline value at point t using
  1206.  * knot vector PKList, and the control points Pdtemp. Returns x, y after the
  1207.  * division by the weight w. Note that Pdtemp points on the first control
  1208.  * point to blend with. The B-spline is of order order.
  1209.  */
  1210. static eval_bspline(t, p_cntr, num_of_points, order, j, contour_kind, x, y)
  1211. double t;
  1212. struct cntr_struct *p_cntr;
  1213. int num_of_points, order, j, contour_kind;
  1214. double *x, *y;
  1215. {
  1216.     int i, p;
  1217.     double ti, tikp, *dx, *dy;      /* Copy p_cntr into it to make it faster. */
  1218.  
  1219.     dx = (double *) alloc((unsigned long) (sizeof(double) * (order + j)),
  1220.                         "contour b_spline");
  1221.     dy = (double *) alloc((unsigned long) (sizeof(double) * (order + j)),
  1222.                         "contour b_spline");
  1223.     /* Set the dx/dy - [0] iteration step, control points (p==0 iterat.): */
  1224.     for (i=j-order; i<=j; i++) {
  1225.         dx[i] = p_cntr -> X;
  1226.         dy[i] = p_cntr -> Y;
  1227.         p_cntr = p_cntr -> next;
  1228.     }
  1229.  
  1230.     for (p=1; p<=order; p++) {        /* Iteration (b-spline level) counter. */
  1231.     for (i=j; i>=j-order+p; i--) {           /* Control points indexing. */
  1232.             ti = fetch_knot(contour_kind, num_of_points, order, i);
  1233.             tikp = fetch_knot(contour_kind, num_of_points, order, i+order+1-p);
  1234.         if (ti == tikp) {   /* Should not be a problems but how knows... */
  1235.         }
  1236.         else {
  1237.         dx[i] = dx[i] * (t - ti)/(tikp-ti) +         /* Calculate x. */
  1238.             dx[i-1] * (tikp-t)/(tikp-ti);
  1239.         dy[i] = dy[i] * (t - ti)/(tikp-ti) +         /* Calculate y. */
  1240.             dy[i-1] * (tikp-t)/(tikp-ti);
  1241.         }
  1242.     }
  1243.     }
  1244.     *x = dx[j]; *y = dy[j];
  1245.     free((char *) dx);
  1246.     free((char *) dy);
  1247. }
  1248.  
  1249. /*
  1250.  * Routine to get the i knot from uniform knot vector. The knot vector
  1251.  * might be float (Knot(i) = i) or open (where the first and last "order"
  1252.  * knots are equal). contour_kind determines knot kind - OPEN_CONTOUR means
  1253.  * open knot vector, and CLOSED_CONTOUR selects float knot vector.
  1254.  * Note the knot vector is not exist and this routine simulates it existance
  1255.  * Also note the indexes for the knot vector starts from 0.
  1256.  */
  1257. static double fetch_knot(contour_kind, num_of_points, order, i)
  1258. int contour_kind, num_of_points, order, i;
  1259. {
  1260.     switch (contour_kind) {
  1261.     case OPEN_CONTOUR:
  1262.         if (i <= order) return 0.0;
  1263.         else if (i <= num_of_points) return (double) (i - order);
  1264.          else return (double) (num_of_points - order);
  1265.     case CLOSED_CONTOUR:
  1266.         return (double) i;
  1267.     default: /* Should never happen */
  1268.         return 1.0;
  1269.     }
  1270. #ifdef sequent
  1271.     return 1.0;
  1272. #endif
  1273. }
  1274.